import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FormConfig } from './form-config.entity';
import { FieldType } from './field-type.entity';
import { CreateFormConfigDto } from './dto/create-form-config.dto';

@Injectable()
export class FormConfigService {
  constructor(
    @InjectRepository(FormConfig)
    private readonly formConfigRepository: Repository<FormConfig>,
    @InjectRepository(FieldType)
    private readonly fieldTypeRepository: Repository<FieldType>,
  ) {}

  async create(createFormConfigDto: CreateFormConfigDto): Promise<FormConfig> {
    const formConfig = new FormConfig();
    formConfig.name = createFormConfigDto.name;
    formConfig.fieldLabels = createFormConfigDto.fieldLabels || {};
    
    // 根据fieldTypeIds获取FieldType实体
    if (createFormConfigDto.fieldTypeIds && createFormConfigDto.fieldTypeIds.length > 0) {
      const fieldTypes = await this.fieldTypeRepository.findByIds(createFormConfigDto.fieldTypeIds);
      formConfig.fieldTypes = fieldTypes;
    }
    
    return this.formConfigRepository.save(formConfig);
  }

  async findAll(): Promise<FormConfig[]> {
    return this.formConfigRepository.find({ relations: ['fieldTypes'] });
  }

  async findOne(id: number): Promise<FormConfig | null> {
    return this.formConfigRepository.findOne({ 
      where: { id }, 
      relations: ['fieldTypes'] 
    });
  }

  async update(id: number, updateFormConfigDto: Partial<CreateFormConfigDto>): Promise<FormConfig | null> {
    const formConfig = await this.findOne(id);
    if (!formConfig) return null;
    
    formConfig.name = updateFormConfigDto.name || formConfig.name;
    formConfig.fieldLabels = updateFormConfigDto.fieldLabels || formConfig.fieldLabels;
    
    // 更新字段类型关联
    if (updateFormConfigDto.fieldTypeIds) {
      const fieldTypes = await this.fieldTypeRepository.findByIds(updateFormConfigDto.fieldTypeIds);
      formConfig.fieldTypes = fieldTypes;
    }
    
    return this.formConfigRepository.save(formConfig);
  }

  async remove(id: number): Promise<void> {
    await this.formConfigRepository.delete(id);
  }
}